<template>
  <PageWrapper contentFullHeight fixedHeight contentClass="main-box">
    
    <a-card class="common-card flex" title="占比分析">
      <CommonDateSearch ref="searchRef5" @search="handleSearch"></CommonDateSearch>
      <div class="chart-content">
        <div class="chart-box" v-for="item in pieTypeList" :key="item.dictCode">
          <Pie :loading="false" :chartData="item.chartData" title="各系统用电量（单位：kWh）占比分析" />
        </div>
        <div class="chart-box" v-for="item in lineTypeList" :key="item.dictCode">
          <Line  :loading="false" :chartData="item.chartData" title="电用量（单位：kWh）" />
        </div>
      </div>
    </a-card>
    <a-card class="common-card flex" title="同环比分析">
      <CommonDateSearch ref="searchRef6" @search="handleSearch1" 
        v-if="initLocationData"
        :disabledOption="['day', 'seven', 'thirty', 'season','halfyear', 'hisYear', 'custom']"
        :defaultSearchValue="defaultSearchValue"
        :extraSearch="extraSearch" />
      <div class="chart-content">
        <div class="chart-box">
          <Line  :loading="false" :chartData="YoYData.chartData" title="同比" >
            <template #tip>
              <div style="display:inline-block;margin-left: 30px;">
                本周期：{{ YoYData.chartData?.current }};上周期：{{ YoYData.chartData?.previous }};同比：{{ formartPercent(YoYData.chartData?.ratio) }}
              </div>
            </template>
          </Line>

        </div>
        <div class="chart-box">
          <Line :loading="false" :chartData="MoMData.chartData" title="环比" >
            <template #tip>
              <div style="display:inline-block;;margin-left: 30px;">
                本周期：{{ MoMData.chartData?.current }};上周期：{{ MoMData.chartData?.previous }};环比：{{ formartPercent(MoMData.chartData?.ratio) }}
              </div>
            </template>
          </Line>
        </div>
      </div>
    </a-card>
  </PageWrapper>
</template>

<script setup>
import Pie from '@/components/Charts/Pie/index.vue'
import Line from '@/components/Charts/Line/index.vue'
import { ref, onMounted, watch, computed, unref } from 'vue'
import { PageWrapper } from '@/components/Page'
import { getEleTypeClassify, getEleTypeRatioClassify, getEleTypeAllReportBuilding,
  getChartVoYoY, getChartVoMoM
 } from '@/api/power/electricity/electricity.ts'
import { getDictListByCode } from '@/api/sys/dict'
import { getClassifyByPatent } from '@/api/collection/classify'
import CommonDateSearch from '@/components/CommonDateSearch/index.vue'
import dayjs from 'dayjs'

defineOptions({ name: 'Kwhpicture' })
const searchRef5 = ref()

const searchInfo = ref()
const dictCode = 'electric_ratio_yoy'
const lineTypeList = ref([])
const pieTypeList = ref([])
const chartList = ref([])
const dataReady = ref(false)
const activeSeriesName = ref(null)
const locationRef = ref([])
const initLocationData = ref(false)
const MoMData = ref({})
const YoYData = ref({})
const defaultSearchValue = {
  queryType: 'week'
}
const extraSearch = ref([
  {
    field: 'classifyId',
    label: '系统选择',
    component: 'Select',
    colProps: { span: 8 },
    componentProps: ({ formModel }) => {
      // formModel.classifyIdList = [locationRef.value[0].classifyId]
      return {
        options: locationRef.value,
        fieldNames: {
          label: 'classifyName',
          value: 'classifyId',
        }
      }
    },
  },
])
const getLocationData = async () => {
  const dictData = await getDictListByCode(dictCode)
  const res = await getClassifyByPatent({parentClassifyId: dictData[0]?.itemCode})
  extraSearch.value[0].defaultValue = res[0]?.classifyId
  locationRef.value = res
  initLocationData.value = true
}
// 接收Pie组件的事件，更新激活名称
const handleLineViewUpdate = (name) => {
  activeSeriesName.value = name
}

const loading = computed(() => {
  return !dataReady.value
})

onMounted(async () => {
  console.log(2)
  getLocationData()
  await getTypeList()
  // searchRef5.value.handleSearch()
})

const getTypeList = async () => {
  // const res = await getDictListByCode(dictCode)
  // res.pop()
  dataReady.value = true
  lineTypeList.value = [{
    loading: false,
    chartData: [],
  }]
  pieTypeList.value = [{
    loading: false,
    chartData: [],
  }]
}
const formartPercent = (num) => {
  if (!num) {
    return '0%'
  }
  return (num * 100).toFixed(2) + '%'
}
const handleSearch = async (params) => {
  if (dataReady.value) {
    searchInfo.value = params
    getLineChartData(params)
    getPieChartData(params)
  } else {
    setTimeout(() => {
      handleSearch(params)
    }, 1000)
  }
}
const handleSearch1 = async (params) => {
  if (dataReady.value) {
    searchInfo.value = params
    getChartVoMoMAndYoYData(params)
  } else {
    setTimeout(() => {
      handleSearch(params)
    }, 1000)
  }
}
// watch(
//   () => unref(searchInfo) ,
//   (newValue) => {
//     if (newValue && Object.values(newValue).length > 0) {
//       handleSearch(newValue)
//     }
//   },
//   { immediate: true },
// )
// 环比

const getChartVoMoMAndYoYData = (searchInfo) => {
  getChartVoMoM({
    ...searchInfo,
  })
  .then((res) => {
    MoMData.value.chartData = {...res,yaxisList: [{name: res.yaxisList[0].name+'环比', data: res.yaxisList[0].ratio},{name: res.yaxisList[0].name+'本期',data: res.yaxisList[0].data}, {name:res.yaxisList[0].name+'上期',data:res.yaxisList[0].oldData}]}
  })
  .finally(() => {
    MoMData.value.loading = false
  })

  getChartVoYoY({
    ...searchInfo,
    // dictCode,
    // itemName: item.itemName,
  })
    .then((res) => {
      YoYData.value.chartData = {...res,yaxisList: [{name: res.yaxisList[0].name+'同比', data: res.yaxisList[0].ratio},{name: res.yaxisList[0].name+'本期',data: res.yaxisList[0].data}, {name:res.yaxisList[0].name+'上期',data:res.yaxisList[0].oldData}]}
    })
    .finally(() => {
      YoYData.value.loading = false
    })
}

const getLineChartData = (searchInfo) => {
  lineTypeList.value.forEach((item) => {
    item.loading = true
    getEleTypeClassify({
      ...searchInfo,
    })
      .then((res) => {
        item.chartData = res
      })
      .finally(() => {
        item.loading = false
      })
  })
}
// 同比
const getPieChartData = (searchInfo) => {
  pieTypeList.value.forEach((item) => {
    item.loading = true
    console.log(1111)
    getEleTypeRatioClassify({
      ...searchInfo,
      // dictCode,
      // itemName: item.itemName,
    })
      .then((res) => {
        const obj = []
        res.titleList.forEach((item, index) => {
          obj.push({
            name: item
          })
        })
        res.valueList.forEach((item, index) => {
          obj[index].value = item
        })
        obj.forEach(item => {
          item.label = {
            formatter: function (data) {
              return `${data.name} (${data.percent.toFixed(0)}%)`
            }
          }
        })
        item.chartData = obj
      })
      .finally(() => {
        item.loading = false
      })
  })
}
</script>

<style scoped lang="scss">
.common-card {
  flex: 1;
  overflow: hidden;
  :deep(.ant-card-body) {
    display: flex;
    flex-wrap: wrap;
    padding: 4px;
    flex: 1;
    overflow: hidden;
    flex-direction: column;
    .chart-content{
      display: flex;
      flex-wrap: wrap;
      padding: 4px;
      flex: 1;
      overflow: hidden;
    }
    .chart-box{
      display: flex;
      flex-wrap: wrap;
      padding: 4px;
      overflow: hidden;
      flex: 1;
      width: 50%;
      height: 100%;
      min-width: 400px;
    }
  }
}
</style>
